﻿using Kingdee.BOS.WebApi.Client;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using static System.Windows.Forms.AxHost;

namespace k3cloud_webapi_sample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btn_query_Click(object sender, EventArgs e)
        {
            K3CloudApiClient client = new K3CloudApiClient("http://192.168.0.19/k3cloud/");
            var ret = client.ValidateLogin("6115be3f79b045", "宋小康", "123456", 2052);
            var result = JObject.Parse(ret)["LoginResultType"].Value<int>();
            // 登陆成功
            if (result == 1)
            {
                string formid = textBox1.Text;
                //var kv = GetBusinessInfo3(client, formid);
                //var json = JsonBaseClass.SerializeObjectToJson(kv);
                //Debug.Print(json);




                var obj = GetBusinessInfo(client, formid);
                var fields = obj.Select(t => new
                {
                    t.Key,
                    Title = t.Name.First().Value,
                    IsExtends = t.Extends != null
                }).ToList();
                var fieldStr = string.Join(",", fields.Select(t => t.Key).ToArray());
                var Bill = new JObject
                {
                    { "FormId" , formid },
                    { "FieldKeys" , fieldStr},
                    { "FilterString " , ""},
                    { "OrderString" , ""},
                    { "TopRowCount" , 0},
                    { "StartRow" , 0},
                    { "Limit" , 10}
                };
                var data = client.ExecuteBillQuery(Bill.ToString());
                var dt = new DataTable();
                foreach (var item in fields)
                {
                    DataColumn dataColumn = new DataColumn();
                    dataColumn.ColumnName = item.Key;
                    dataColumn.Caption = item.Title;
                    dt.Columns.Add(dataColumn);
                }
                //List<dynamic> list = new List<dynamic>();

                for (int i = 0; i < data.Count; i++)
                {
                    DataRow dataRow = dt.NewRow();
                    //dynamic newobj = new ExpandoObject();
                    //var _provider = newobj as IDynamicMetaObjectProvider;
                    for (int j = 0; j < fields.Count; j++)
                    {
                        if (data[i][j] == null) { continue; }
                        //_provider.Value(fields[j].Key, data[i][j]);
                        if (fields[j].IsExtends)
                        {
                            var exList = obj.Where(t => t.Key.Equals(fields[j].Key)).Select(t => t.Extends).FirstOrDefault();
                            if (exList != null)
                            {
                                string value = exList.Where(t => t.Value.Equals(data[i][j].ToString())).Select(t => t.Caption).FirstOrDefault();
                                dataRow[fields[j].Key] = value;
                            }
                        }
                        else
                        {
                            dataRow[fields[j].Key] = data[i][j];
                        }
                    }
                    //list.Add(newobj);
                    dt.Rows.Add(dataRow);
                }


                //var json = JsonBaseClass.SerializeObjectToJson(list);
                //Debug.Print(json);



                dataGridView1.DataSource = dt;
                foreach (DataGridViewColumn itemCol in dataGridView1.Columns)
                {
                    try
                    {
                        itemCol.HeaderText = dt.Columns[itemCol.Name].Caption;
                    }
                    catch
                    {
                    }
                }
            }
        }

        /// <summary>
        /// 元数据
        /// </summary>
        private List<KingdeeFieldResult> GetBusinessInfo(K3CloudApiClient client, string formId)
        {
            var bInfo = client.QueryBusinessInfo($"{{FormId:'{formId}'}}");
            List<KingdeeFieldResult> list = null;
            if (bInfo != null)
            {
                var obj = JsonBaseClass.DeserrializeJsonToObject<K3ApiResult<BusinessInfoResult>>(bInfo);
                if (obj.Result.ResponseStatus.IsSuccess)
                {
                    list = new List<KingdeeFieldResult>();
                    obj.Result.NeedReturnData.Entrys.ForEach((r) =>
                    {
                        r.Fields.ForEach((f) =>
                        {
                            if (f.LookUpObjectFormId != null)
                            {
                                var pkFields = GetBusinessInfo2(client, f.LookUpObjectFormId);
                                var kfResult = pkFields.Where(t => t.Key.Equals("FNumber") || t.Key.Equals("FName")).OrderByDescending(t => t.Key).FirstOrDefault();
                                if (kfResult != null)
                                {
                                    f.Key += ("." + kfResult.Key);
                                }
                            }
                            list.Add(f);
                        });
                    });
                }
            }
            //list = list.Where(t => t.LookUpObjectFormId != null).ToList();
            //var json = JsonBaseClass.SerializeObjectToJson(list);
            return list;
        }

        private List<KingdeeFieldResult> GetBusinessInfo2(K3CloudApiClient client, string formId)
        {
            var bInfo = client.QueryBusinessInfo($"{{FormId:'{formId}'}}");
            List<KingdeeFieldResult> list = null;
            if (bInfo != null)
            {
                var obj = JsonBaseClass.DeserrializeJsonToObject<K3ApiResult<BusinessInfoResult>>(bInfo);
                if (obj.Result.ResponseStatus.IsSuccess)
                {
                    list = new List<KingdeeFieldResult>();
                    obj.Result.NeedReturnData.Entrys.ForEach((r) =>
                    {
                        list.AddRange(r.Fields);
                    });
                }
            }
            return list;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            K3CloudApiClient client = new K3CloudApiClient("http://localhost:1200/k3cloud/");
            var ret = client.ValidateLogin("61271b176f110c", "宋小康", "123456", 2052);
            var result = JObject.Parse(ret)["LoginResultType"].Value<int>();
            // 登陆成功
            if (result == 1)
            {
                var ds = client.Execute<string>("Caraya.MFG.BusinessPlugIn.ApiStockDetail.Query,Caraya.MFG.BusinessPlugIn", new object[] { 100117 });
                Console.WriteLine(ds);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            K3CloudApiClient client = new K3CloudApiClient("https://gzweibo.ik3cloud.com/k3cloud/");
            var ret = client.ValidateLogin("20181217163100", "宋小康", "sim-137517", 2052);
            var result = JObject.Parse(ret)["LoginResultType"].Value<int>();
            // 登陆成功
            if (result == 1)
            {
                string formid = "ora_CGWLJSBB";
                var jobj = new
                {
                    parameters = new List<object>()
                    {
                        formid,
                        new
                        {
                            FieldKeys="FSALEORDERNO,FPRODUCTNAME,FMODEL,FQUANTITYOFORDER,FNUMBERATOR,FDENOMINATOR,FREQUIREDQUANTITY,FDATE,FMATERIALNAME,FSPECIFICATION,FINVENTORYQUANTITY,FUNCLAIMEDNUMBER,FSTOCKNAME,FSTOCKSTATUS,FREMAINSTOCKINQTY,FENDQTY",
                            StartRow=0,
                            Limit=200,
                            Model = new
                            {
                                FMATERIALID=K3Number.Parse("ABGAT0001-0201")
                            }
                        }
                    }
                };
                //var json = JsonConvert.SerializeObject(jobj);
                var json = /*lang=json,strict*/ @"
                                        {
                        ""FieldKeys"": ""FSALEORDERNO,FPRODUCTNAME,FMODEL,FQUANTITYOFORDER,FNUMBERATOR,FDENOMINATOR,FREQUIREDQUANTITY,FDATE,FMATERIALNAME,FSPECIFICATION,FINVENTORYQUANTITY,FUNCLAIMEDNUMBER,FSTOCKNAME,FSTOCKSTATUS,FREMAINSTOCKINQTY,FENDQTY"",
                        ""SchemeId"": """",
                        ""StartRow"": 0,
                        ""Limit"": 2000,
                        ""IsVerifyBaseDataField"": ""true"",
                        ""Model"": {
                            ""FMATERIALID"": {
                                ""FNumber"": ""ABGAT0001-0201""
                            }
                        }
                    }
                    ";
                var ds = client.GetSysReportData(formid, json);
                Console.WriteLine(ds);
            }
        }
    }
}
